import {Component, OnDestroy, OnInit} from '@angular/core';
import { Response } from '@angular/http';

import {SliderService} from './slider.service';

@Component({
  selector: 'app-slider-show',
  templateUrl: './slider-show.component.html',
  styleUrls: ['./slider-show.component.less'],
  providers: [SliderService]
})
export class SliderShowComponent implements OnInit, OnDestroy {
  images;
  currentIndex = 1;
  totalNumber: number;
  autoplayInterval;
  constructor(private sliderService: SliderService ) { }

  ngOnInit() {
    this.sliderService.getImages().subscribe(
      (response: Response) => {
        const data = response.json();
        this.images = data.data.images;
        this.totalNumber = this.images.length;
        this.autoplay();
      }
    );
  }
  prev() {
    if (this.currentIndex === 1) {
      this.currentIndex = this.totalNumber;
    }else {
      this.currentIndex -= 1;
    }
  }
  nextPage() {
    if (this.currentIndex === this.totalNumber) {
      this.currentIndex = 1;
    }else {
      this.currentIndex += 1;
    }
  }
  gotoPage(index: number) {
    this.currentIndex = index + 1;
  }
  autoplay() {
    this.autoplayInterval = setInterval(
      () => {
        this.nextPage();
      }, 2000);
  }
  ngOnDestroy() {
    clearInterval(this.autoplayInterval);
  }
  pause() {
    clearInterval(this.autoplayInterval);
  }
  continue() {
    this.autoplay();
  }
}
